<template>
    <div>
        <el-row>
            <el-col :span="24" >
                <el-button v-for="item in products" size="small" :subjectid="item.id" :type="item.tagcss"  v-on:click="changetag" plain>
                    <el-badge v-if="item.selected" is-dot class="item">{{item.title}}</el-badge>
                    <template v-else>
                        {{item.title}}
                    </template>
                </el-button>
                <template v-if="mode=='show'">
                    <!-- 这些按钮需要定义组件 -->
                    <!-- <router-link :to="'/contentedit/'+subjectid+'/'+attributeid" style="float:right;padding-left:8px;" >
                    <el-button  size="small"  style="float:right;" icon="el-icon-search" circle></el-button>
                    </router-link> -->
                    <!-- <router-link :to="'/contentedit/'+subjectid+'/'+attributeid" style="float:right;padding-left:8px;" >
                        <el-button  size="small"  type="primary" icon="el-icon-edit"  circle></el-button>
                    </router-link> -->
                    <!-- <el-button  size="small"  style="float:right;margin-left:8px;" type="success" icon="el-icon-check" v-on:click="btnClick($event, '提交')" circle></el-button> -->
                    <!-- <el-button  size="small"  style="float:right;margin-left:8px;" type="warning" icon="el-icon-star-off" v-on:click="btnClick($event, 'collection')" circle></el-button> -->
                    <!-- <el-button  size="small"  style="float:right;" type="danger" icon="el-icon-delete" v-on:click="btnClick($event, 'delete')" circle></el-button> -->
                </template>
                <template v-else>
                    <el-button type="danger"  size="small" style="float:right;margin-left:8px;"  v-on:click="btnClick($event, 'exit')">退出<i class="el-icon-arrow-right"></i></el-button>
                    <el-button type="success"  size="small" style="float:right;margin-left:8px;"   v-on:click="btnClick($event, 'save')">保存<i class="el-icon-plus el-icon-check"></i></el-button>
                </template>
            </el-col>
            <el-col :span="24" style="margin-top:10px;">
                <el-alert
                    :title="attribute.FullName"
                    :type="attribute.type"
                    :description="attribute.Content"
                    :closable="false">
                </el-alert>
            </el-col>
        </el-row>
        <el-row :gutter="12" style="margin-top:10px;">
            <el-col :span="24" v-for="item in topContent">
                <el-card shadow="always" >
                <b>{{item.title}}</b> <span style="font-size:10px;color:gary;">{{item.resume}}</span>
                <hr style="height:1px; border:0px; border-bottom:1px solid #e3e3e3;"/>
                <div style="border:0px solid #e3e3e3; overflow:auto;">
                    <mavonEditor v-model="item.content" :mode="mode" :height="330"></mavonEditor>
                </div>
                </el-card>
            </el-col>
        </el-row>
        <el-row :gutter="12" style="margin-top:10px;" :class="iscollapse?'waterfall2':'waterfall'">
            <el-col :sx="24" :sm="24" :md="24" :lg="24" :xl="24"  class="waterfall_item" v-for="item in otherContents">
                <el-card shadow="hover" >
                {{item.title}} <span style="font-size:10px;color:gary;">{{item.resume}}</span>
                <hr style="height:1px; border:0px; border-bottom:1px solid #e3e3e3;"/>
                <div style="border:0px solid #e3e3e3; overflow:auto;" >
                     <mavonEditor v-model="item.content" mode="show" :height="330"></mavonEditor>
                </div>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script>
import mavonEditor from "../common/ui/editor";
import { page } from "../../data/base_data";
import { baseUrl, baseImgPath } from "../../config/env";
// import Marked from 'marked';
export default {
  data() {
    return {
      loading: [],
      isloading: true,
      currentID: 0,
      baseDate: {
        curpage: {}
      },
      html: "",
      attribute: {
        FullName: "",
        ShortName: "",
        EnName: "",
        Tag: "",
        Content: "",
        type: "success"
      },
      products: [],
      contents: []
    };
  },
  components: {
    mavonEditor
  },
  computed: {
    topContent: function() {
      var id = this.currentID;
      return this.contents.where(function(item) {
        return item.id == id;
      });
    },
    otherContents: function() {
      var id = this.currentID;
      return this.contents.where(function(item) {
        return item.id != id;
      });
    }
  },
  props: ["subjectid", "attributeid", "mode", "iscollapse"],
  watch: {
    $route(to, from) {
      console.log(
        "subjectid:" + this.subjectid + "; attributeid:" + this.attributeid
      );
      this.loadSubjectAttribute();
    }
  },
  methods: {
    startLoading: function(msg) {
      this.loading = this.$loading({
        lock: true,
        text: msg || "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.0)"
      });
    },
    stopLoading: function() {
      this.loading.close();
    },
    loadSubjectAttribute: function() {
      this.startLoading("随便加载中...");
      //初始化参数
      (this.products = []), (this.contents = []);
      var rule = [
        {
          Field: "SubjectID",
          Value: this.subjectid,
          Operate: 3
        }
      ];
      if (this.attributeid && this.attributeid > 0) {
        rule.push({
          Field: "Id",
          Value: this.attributeid,
          Operate: 3
        });
      }
      this.baseDate.curpage.FilterGroup.Rules = rule;
      //post数据
      this.$http
        // .post(
        //   baseUrl + "api/Admin/ContrastAttribute/Read",
        //   this.baseDate.curpage
        // )
        .post(baseUrl + "api/Admin/ContrastAttribute/GetSubjectAttribute", [
          this.subjectid
        ])
        .then(
          function(res) {
            if (res.body.Rows.length > 0) {
              var attrid = this.attributeid;
              if (!attrid || attrid == 0) {
                this.attribute = res.body.Rows[0];
                //this.attributeid = this.attribute.Id;
              } else {
                this.attribute = res.body.Rows.where(function(item) {
                  return item.Id == attrid;
                })[0];
              }
              this.attribute.type = "success";
              this.loadSubjectProject();
            } else this.stopLoading();
          },
          function(res) {
            alert("操作数据获取失败");
            this.stopLoading();
          }
        );
    },
    loadSubjectProject: function() {
      this.baseDate.curpage.FilterGroup.Rules = [
        {
          Field: "SubjectID",
          Value: this.subjectid,
          Operate: 3
        }
      ];
      this.contents = [];
      //post数据
      this.$http
        .post(
          baseUrl + "api/Admin/ContrastProduct/Read",
          this.baseDate.curpage,
          { emulateJSON: false }
        )
        .then(
          function(res) {
            var tempcontents = [];
            if (res.body.Rows.length > 0) {
              for (let index = 0; index < res.body.Rows.length; index++) {
                const element = res.body.Rows[index];
                tempcontents.push({
                  id: element.Id,
                  title: element.ShortName,
                  content: "",
                  valueid: 0,
                  resume: element.Resume,
                  selected: index == 0 ? true : false,
                  tagcss: this.setTagCss(index)
                });
              }
              this.products = tempcontents;
              this.loadSubjectProjectValue(this.attribute.Id, tempcontents);
            } else this.onAddRow();
          },
          function(res) {
            alert("操作数据获取失败");
            this.stopLoading();
          }
        );
    },
    setTagCss: function(i) {
      var _i = i % 5;
      var arry = ["", "success", "info", "warning", "danger"];
      return arry[_i];
    },
    loadSubjectProjectValue: function(AttributeID, tempcontents) {
      var rule = [
        { Field: "AttributeID", Value: AttributeID, Operate: 3 }
        // { Field: "ProductID", Value: ProductID,  Operate: 3  }
      ];
      this.baseDate.curpage.FilterGroup.Rules = rule;
      this.baseDate.curpage.PageCondition.SortConditions = [
        {
          SortField: "Id",
          ListSortDirection: 0
        }
      ];
      this.contents = [];
      //post数据
      this.$http
        .post(
          baseUrl + "api/Admin/ContrastProductAttribute/Read",
          this.baseDate.curpage
        )
        .then(
          function(res) {
            for (let index = 0; index < tempcontents.length; index++) {
              const products = tempcontents[index];
              var value = res.body.Rows.where(w => {
                return w.ProductID == products.id;
              });
              if (value && value.length > 0) {
                products.content = value[0].Content;
                products.valueid = value[0].Id;
              }
            }
            this.contents = tempcontents;
            this.currentID = tempcontents[0].id;
            this.isloading = false;
            this.stopLoading();
          },
          function(res) {
            alert("值获取失败");
            this.stopLoading();
          }
        );
    },
    postSaveDate: function() {
      this.startLoading("数据保存中...");
      var that = this;
      var postData = this.contents.select(item => {
        return {
          Id: item.valueid,
          AttributeID: that.attribute.Id,
          ProductID: item.id,
          Resume: item.resume,
          Content: item.content
        };
      });
      this.$http
        .post(
          baseUrl + "api/Admin/ContrastProductAttribute/CreateAndUpdate",
          postData
        )
        .then(
          function(res) {
            if (res.body.Type == 200 || res.body.Type == 203) {
              this.$message({
                message: "内容设置成功，" + res.body.Content,
                type: "success"
              });
              this.$router.push({
                path: `/contentshow/${this.subjectid}/${this.attribute.Id}`
              }); // -> /user/123
            } else {
              this.$message.error("保存失败！" + res.body.Content);
              this.stopLoading();
            }
          },
          function(res) {
            alert("值获取失败");
            this.stopLoading();
          }
        );
    },
    exitPage: function() {
      this.$router.go(-1);
    },
    loadDate: function() {
      this.loadSubjectAttribute();
      // this.attribute.FullName = "警告";
      // this.attribute.Content = "你得选择右侧属性，否则我不知道你要看什么！";
      // this.attribute.type = "error";
      // this.$alert('你得选择右侧属性，否则我不知道你要看什么！', '警告', {
      //     confirmButtonText: '知道了'
      // });
    },
    changetag: function(event) {
      var _subjectid = event.currentTarget.getAttribute("subjectid");
      var _i = 1;
      this.contents.forEach(element => {
        element.selected = element.id == _subjectid;
        element.sort = element.id == _subjectid ? 1 : _i;
        _i++;
      });
      this.currentID = _subjectid;
    },
    btnClick: function(event, action) {
      if (action == "save") {
        this.postSaveDate();
      } else if (action == "exit") {
        this.exitPage();
      } else {
        this.$message({
          message: "点点点点，再点我也不会给你" + msg + "!",
          type: "warning"
        });
      }
    }
  },
  mounted: function() {
    this.baseDate.curpage = page;
    this.loadSubjectAttribute();
  }
};
</script>

<style scoped>
.el-tag {
  margin-right: 6px;
}
/*一个内容层*/
.el-card {
  min-height: 240px;
}


/*瀑布流层*/
.waterfall {
  -moz-column-count: 2; /* Firefox */
  -webkit-column-count: 2; /* Safari 和 Chrome */
  column-count: 2;
  -moz-column-gap: 1em;
  -webkit-column-gap: 1em;
  column-gap: 1em;
}
.waterfall2 {
  -moz-column-count: 1; /* Firefox */
  -webkit-column-count: 1; /* Safari 和 Chrome */
  column-count: 1;
  -moz-column-gap: 1em;
  -webkit-column-gap: 1em;
  column-gap: 1em;
}
/*一个内容层*/
.waterfall_item {
  margin: 0 0 1em 0;
  -moz-page-break-inside: avoid;
  -webkit-column-break-inside: avoid;
  break-inside: avoid;
}
</style>